local null_ls = require "null-ls"
local helpers = require "null-ls.helpers"

local severities = {
  Hint = helpers.diagnostics.severities.hint,
  Warning = helpers.diagnostics.severities.warning,
  Error = helpers.diagnostics.severities.error,
}

return {
  method = null_ls.methods.DIAGNOSTICS,
  filetypes = { "nim" },
  generator = null_ls.generator {
    command = "nim",
    args = {
      "check",
      "--colors:off",
      "--hint:Conf:off",
      "--hint:SuccessX:off",
      "--processing:off",
      "--unitsep:on",
      "-",
    },
    to_stdin = true,
    from_stderr = true,
    cwd = function(params)
      return params.bufname:match "(.*[/\\])"
    end,
    format = "raw",
    on_output = function(params, done)
      local output = params.output or ""
      local diagnostics = {}
      for message in output:gmatch("[^" .. string.char(31) .. "]+") do
        local row, col, severity, text = message:match "stdinfile.nim%((%d+), (%d+)%) (%w+): (.*)"
        if text then
          table.insert(diagnostics, {
            row = row,
            col = col,
            source = "nimcheck",
            message = text,
            severity = severities[severity],
          })
        end
      end
      done(diagnostics)
    end,
  },
}
